package org.demo.tmp;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.demo.tmp.sub.TempTest;


public class Main implements Serializable{
	//private static Log logger = LogFactory.getLog(Main.class);
	
	public static void main(String... args) throws Exception {
		
		Timer timer = new Timer();
		
		/* 3 秒后执行指定任务 [只执行一次]*/
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				// 
				System.out.println(" -- another method --");
			}
		}, TimeUnit.SECONDS.toMillis(3));
		
		/* 每秒执行一次指定任务 */
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				// 
				System.out.println(">> " + System.currentTimeMillis());
			}
		}, 0, 1000);
		// ------		
		System.out.println("---------------------");
	}	
	public static String conver(String str, String insertChar, int insertNumber) { 
		StringBuilder sb = new StringBuilder();
		int i = 1, length = str.length();
		while(i <= length){
			sb.insert(0,str.charAt(length - i));
			if ((i != length) && (i%insertNumber == 0)){
				sb.insert(0,insertChar);
			}
			i++;
		}
		return sb.toString();
    } 
	class ParameterSet<K,V>{
		private Map<K,List<V>> map = new HashMap<K,List<V>>();
		/**
		 * 添加一个元素
		 * @param key
		 * @param value
		 */
		public void put(K key, V value){
			List<V> list = map.get(key);
			if (list == null){
				list = new ArrayList<V>();
			}
			list.add(value);
			map.put(key, list);
		}
		/**
		 * 删除指定的 key - value
		 * @param key
		 * @param value
		 * @return
		 */
		public boolean remove(K key,V value){
			List<V> list = map.get(key);
			if (list == null || list.size() == 0){
				return true;
			}
			boolean result = list.remove(value);
			if (result && list.size() == 0){
				map.remove(key);
			}
			return result;
		}
		/**
		 * 删除 key 指定的所有 value
		 * @param key
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public V[] removeAll(K key){
			List<V> list = map.remove(key);
			if (list == null || list.size() == 0){
				return null;
			}
			Class<V> clazz = (Class<V>) list.get(0).getClass();
			return list.toArray((V[])Array.newInstance(clazz, list.size()));
		}
		/**
		 * 清空所有内容
		 */
		public void clear(){
			map.clear();
		}
		/**
		 * 获取对应的 value
		 * @param key
		 * @return
		 */
		public V getParameter(K key){
			List<V> list = map.get(key);
			if (list == null || list.size() == 0){
				return null;
			}
			return list.get(0);
		}
		/**
		 * 返回对应的一个数组
		 * @param key
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public  V[] getParameterValues(K key){
			List<V> list = map.get(key);
			if (list == null || list.size() == 0){
				return null;
			}
			Class<V> clazz = (Class<V>) list.get(0).getClass();
			return list.toArray((V[])Array.newInstance(clazz, list.size()));
		}
		/**
		 * toString
		 */
		@Override
		public String toString() {
			return map.toString();
		}
	}
	/**
	 * 重命名文件
	 * @param oldName
	 * @param newName
	 * @return
	 */
	public static String renameFile(String oldName, String newName){
		String filePath = "d:\\Temp";
		File oldFile = new File(filePath + "/" + oldName);
		File newFile = new File(filePath + "/" + newName);
		if (!oldFile.exists()){
			return "重命名失败:源文件[" + oldFile.getName() + "]已不存在";
		}
		if (newFile.exists()){
			return "重命名失败:目标文件[" + newFile.getName() + "]已存在";
		}
		if (!oldFile.renameTo(newFile)){
			return "重命名失败:" + oldFile.getName() + " -> " + newFile.getName();
		}
		return "";
	}
	/**
	 * 字符串前缀填充
	 * @param max 最大长度
	 * @param ch  填充字符
	 * @param value 原始值
	 * @return
	 */
	public static String fillPrefix(int max, char ch, String value){
		if (value == null || value.length() >= max){
			return value;
		}
		StringBuilder sb = new StringBuilder(value);
		for (int i=value.length(); i<max; i++){
			sb.insert(0, ch);
		}
		return sb.toString();
	}	
	/**
	 * 字符串前缀填充
	 * @param max 最大长度
	 * @param ch  填充字符
	 * @param value 原始值
	 * @return
	 */
	public static String fillPrefix1(int max, char ch, String value){
		if (value == null || value.length() >= max){
			return value;
		}
		StringBuilder sb = new StringBuilder(value);
		for (int i = value.length(); i<max; i++){
			sb.insert(0,ch);
		}		
		return sb.toString();
	} 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int index;
	
	public Main(){
		System.out.println("in the main constructor().");
	}
	public Main(int i){
		index = i;
		System.out.println("in the main constructor(i).");
	}
	/**
	 * 校验 email
	 * @param email
	 * @return
	 */
	public static boolean validateEmail(String email){
		String regex = "([a-z\\d]+[_|\\-|\\.]?)*[a-z\\d]+@(([a-z\\d]+[\\-]?)*[a-z\\d]+\\.)+[a-z]{2,3}";
		Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(email);
		return m.matches();	
	}
	/**
	 * 获取数据库连接
	 * @return
	 */
	public Connection getMySqlConnection()throws Exception{
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://10.162.11.245:3306/test";
		String user = "root";
		String pass = "root";
		// 
		Class.forName(driver);
		return DriverManager.getConnection(url, user, pass);
	} 
	/**
	 * 获取数据库连接
	 * @return
	 */
	public Connection getConnection()throws Exception{
		String driver = "com.ibm.db2.jcc.DB2Driver";
		String url = "jdbc:db2://10.162.11.134:50000/sample";
		String user = "db2admin";
		String pass = "db2admin";
		// 
		Class.forName(driver);
		return DriverManager.getConnection(url, user, pass);
	}
	/**
	 * 判断表是否存在
	 * @param conn
	 * @param tableName
	 * @return
	 */
	public boolean existTable(Connection conn,String tableName){
		boolean exist = false;
		String sql = "select * from " + tableName + " where 1=0";
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			stmt.executeQuery(sql);
			exist = true;
		} catch(SQLException e){
			exist = false;
		} finally {
			try { if(stmt != null)stmt.close(); } catch (Exception e){}
		}
		// print
		System.out.println("Table " + tableName + " exist: " + exist);
		// return
		return exist;
	}
	/**
	 * 创建表
	 * @param conn
	 * @throws SQLException 
	 */
	public void createTable(Connection conn) throws SQLException{
		String sql = "create table student("
			       + "  id   varchar(20) not null,"
			       + "  name varchar(32) not null,"
			       + "  age  integer" 
			       + ")";
		Statement stmt = conn.createStatement();
		stmt.execute(sql);
		// print
		System.out.println("Create table : student");
	}
	/**
	 * 删除表
	 * @param conn
	 * @param tableName
	 */
	public void dropTable(Connection conn,String tableName){
		String sql = "drop table " + tableName;
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			stmt.execute(sql);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try { if (stmt != null)stmt.close(); } catch (Exception e){}
		}
		// print
		System.out.println("Drop table: " + tableName);
	}
	/**
	 * 创建存储过程
	 * @param conn
	 */
	public void createProcedure(Connection conn){
		String sql = "create procedure tmp_proc (out curdtime varchar(19)) "
		           + "specific tmp_proc "
		           + "begin "
		           + "declare cur cursor for "
		           + "    select to_char(current timestamp,'yyyy-MM-dd HH24:mi:ss') as dtime from sysibm.sysdummy1;"
		           + "open cur; "
		           + "fetch cur into curdtime; "
		           + "close cur;"
		           + "end";
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			stmt.execute(sql);
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try { if (stmt != null)stmt.close();} catch(Exception e){}
		}
	}
	/**
	 * 调用存储过程
	 * @param conn
	 */
	public void callProcedure(Connection conn){
		String sql = "call tmp_proc(?)";
		CallableStatement cstmt = null;
		try {
			cstmt = conn.prepareCall(sql);
			cstmt.registerOutParameter(1, Types.VARCHAR);
			cstmt.execute();
			String result = cstmt.getString(1);
			System.out.println("procedure result: " + result);
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try { if (cstmt != null)cstmt.close();} catch (Exception e){}
		}
	}
	/**
	 * 删除存储过程
	 * @param conn
	 */
	public void dropProcedure(Connection conn){
		String sql = "drop specific procedure tmp_proc";
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			stmt.execute(sql);
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try { if (stmt != null)stmt.close();} catch (Exception e){}
		}
	}
	/**
	 * 创建触发器
	 * @param conn
	 */
	public void createTrigger(Connection conn){
		String sql = "create trigger trg_upd_stu "
			       + "before update on student "
			       + "referencing new as n "
			       + "for each row "
			       + "begin "
			       + "if (n.age is null or n.age < 0) then "
			       + "  set n.age = 0; "
			       + "end if; "
			       + "end";
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			stmt.execute(sql);
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try { if (stmt != null)stmt.close();} catch (Exception e){}
		}	
	}
	/**
	 * 删除触发器
	 * @param conn
	 */
	public void dropTrigger(Connection conn){
		String sql = "drop trigger trg_upd_stu";
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			stmt.execute(sql);
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try { if (stmt != null)stmt.close();} catch (Exception e){}
		}
	}
	/**
	 * 执行增改查删
	 * @param conn
	 */
	public void executeCURD(Connection conn){
		String insert = "insert into student values(?,?,?)";
		String update = "update student set age = ? where id = ?";
		String select = "select * from student";
		String delete = "delete from student";
		// 
		PreparedStatement pstmt = null;
		Statement stmt = null;
		try {
			// insert
			pstmt = conn.prepareStatement(insert);
			pstmt.setString(1, "1");
			pstmt.setString(2, "zhangsan");
			pstmt.setInt(3, 22);
			pstmt.addBatch();
			pstmt.setString(1, "2");
			pstmt.setString(2, "lisi");
			pstmt.setInt(3, 23);
			pstmt.addBatch();
			pstmt.executeBatch();
			// update
			pstmt = conn.prepareStatement(update);
			pstmt.setInt(1, -1);
			pstmt.setString(2, "1");
			pstmt.executeUpdate();
			// select
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(select);
			while (rs.next()){
				String name = rs.getString("NAME");
				int age = rs.getInt("AGE");
				System.out.println("name: " + name + " age: " + age);
			}
			// delete 
			stmt.executeUpdate(delete);
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try { if (stmt != null)stmt.close();} catch (Exception e){}
			try { if (pstmt != null)pstmt.close();} catch (Exception e){}
		}
	};
};